package com.axend.lib_base.base.fragment

import android.os.Build
import android.os.Bundle
import android.view.Gravity
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.annotation.RequiresApi
import androidx.databinding.ViewDataBinding
import com.axend.lib_base.base.vm.BaseViewModel
import com.axend.lib_base.ext.dip2px
import com.axend.lib_base.ext.orDefault
import com.axend.lib_base.ext.toFloatOrDefault
import com.axend.lib_base.help.TempProcess
import com.axend.lib_base.view.RectangleView
import com.guide.zx03c.GuideInterface
import com.guide.zx03c.UsbStatusInterface
import com.guide.zx03c.view.IrSurfaceView
import java.lang.Integer.max
import java.lang.Integer.min
import java.util.PriorityQueue

/**
 * @description红外摄像头基类
 * @author admins
 * @time 2024/6/25 11:52
 */
abstract class BaseVVDInfraredCameraFragment<VM : BaseViewModel, VB : ViewDataBinding> :
    BaseVVDFragment<VM, VB>() {
    protected lateinit var mIrSurfaceView: IrSurfaceView
    protected var guideInterface: GuideInterface? = null
    protected var maxIndex: Int = 0
    protected val rotateType = 0

    /**
     * 原始红外视频分辨率：192*256
     */
    protected val SRC_WIDTH = 192
    protected val SRC_HEIGHT = 256

    protected lateinit var mHighCrossView: ImageView


    protected var irSurfaceViewWidth: Float = 0f
    protected var irSurfaceViewHeight: Float = 0f

    /**
     * 体表最高温
     */
    protected var maxTempStr = "0"
    protected var maxX: Int = 0
    protected var maxY: Int = 0
    protected var vivoTempStr = "0"

    protected val FRAME: Int = 5
    protected var count = 0

    /*新增体表最高温数据处理相关参数2024-10-10 Cai*/
    protected var filteredMaxTemp: Float = 0f
    protected var filteredMaxTempStr = "0"
    protected var firstMaxTempStr = "0"
    protected var maxTempCountF = 0
    protected var maxTempCountC = 0
    protected var tempList: MutableList<Float>? = mutableListOf()
    protected val dataSize = 60
    protected var isClearListC = false
    protected var isClearListF = false
    protected lateinit var tempProcess: TempProcess
    protected val bodyMaxTempNoiseThreshold = 0.5f // 相邻数据平滑差值

    protected var y16W = 0
    protected var y16H: Int = 0
    protected var centerX = y16W / 2 // 圆心X坐标

    protected var centerY: Int = y16H / 2 // 圆心Y坐标

    protected val radius = 38 // 圆的半径--温度矩阵不能超过红外短边的一半=192/2=96
    protected var mY16Frame: ShortArray? = null
    protected var mSyncY16Frame: ShortArray? = null

    //    protected lateinit var circleView: CircleView
    protected lateinit var rectangleView: RectangleView
    protected lateinit var maxTempArray: List<Double>
    protected var vivoMaxTemp: Double? = null

    protected var keepCount = 0
    protected val keepCountThreshold = 5
    protected val tempDiff = 2.5f

    protected var isRegisterUsbReceiver = false


    abstract fun setScale(): Int

    abstract fun setUsbStatusInterface(): UsbStatusInterface

    abstract fun setImageCallBackInterface(): GuideInterface.ImageCallBackInterface

    override fun init(savedInstanceState: Bundle?) {
        initInfrared()
    }


    private fun initInfrared() {
        /*初始化红外摄像头相关*/
        mIrSurfaceView = IrSurfaceView(mActivity).apply {
            layoutParams = FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT,
                Gravity.CENTER
            )
            setMatrix((dip2px(setScale()) / (3 * 256)), 0f, 0f)
        }
        guideInterface = GuideInterface.getInstance().apply {
            guideCoreInit(mActivity, 0, 3f, rotateType)
            setEnableSR(false)
            setImageEnhance(false)
            /*镜像*/
            setFilpY(false)
            stopSDKDebug()
        }
        /*最高温图标*/
        mHighCrossView = ImageView(mActivity).apply {
            setImageResource(com.axend.lib_base.R.drawable.high_cross)
            scaleType = ImageView.ScaleType.CENTER_INSIDE
        }
        /*初始化温度数据处理类*/
        tempProcess = TempProcess()

        //原始红外视频的分辨率是192*256

        // 不显示版本号
//        mSDKVersionTextView.setText("SDK 版本号: " + mGuideInterface.getVersion());

        //原始红外视频的分辨率是192*256
        mY16Frame = ShortArray(SRC_WIDTH * SRC_HEIGHT)
        mSyncY16Frame = ShortArray(SRC_WIDTH * SRC_HEIGHT)
        getY16WY16H()
//        circleView = CircleView(requireContext())


    }


    /**
     * 开始获取红外图像
     */
    protected fun startGetImage() {
        guideInterface?.let {
            it.registUsbPermissions()
            it.registUsbStatus(setUsbStatusInterface())
            isRegisterUsbReceiver=true
            val ret: Int = it.startGetImage(setImageCallBackInterface())
            if (ret < 0) {
                setUsbStatusInterface().usbDisConnect()
            }
        }
    }

    /**
     * 停止获取红外图像
     */
    protected fun stopGetImage() {
        guideInterface?.let {
            it.stopGetImage()
            if (isRegisterUsbReceiver){
                it.unRegistUsbPermissions()
                it.unRegistUsbStatus()
            }
            isRegisterUsbReceiver = false
        }
    }


    /**
     * 从y16数组中获取最大的Y16的值
     */
    protected fun getMaxY16(y16Arr: ShortArray): Short {
        var maxY16 = Short.MIN_VALUE
        val length = y16Arr.size

        for (i in 0 until length) {
            if (maxY16 < y16Arr[i]) {
                maxY16 = y16Arr[i]
                maxIndex = i
            }
        }

        return maxY16
    }

    /*相机初始化*/ //    public View initCamera() {
    //        mSurfaceView = findViewById(R.id.final_camera_surfaceView);
    //
    //        mSurfaceHolder = mSurfaceView.getHolder();
    //        mSurfaceHolder.addCallback(this);
    ////        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    //
    //        return mSurfaceView;
    //    }
    private fun getY16WY16H() {
        if (rotateType == 1 || rotateType == 3) {
            y16W = SRC_WIDTH
            y16H = SRC_HEIGHT
        } else {
            y16W = SRC_HEIGHT
            y16H = SRC_WIDTH
        }
        /*设置温度矩阵的圆形区域大小*/
        centerX = y16W / 2 // 圆心X坐标
        centerY = y16H / 2 // 圆心Y坐标
    }


    protected fun getCircleTemp() {
        System.arraycopy(mY16Frame, 0, mSyncY16Frame, 0, mY16Frame?.size!!)


        val tempArray =
            FloatArray((2 * radius + 1) * (2 * radius + 1)) // 估计圆形区域的大小，温度矩阵限制大小为y16W*y16H
        var tempY16Array = ShortArray(tempArray.size)
        var tempXArray = IntArray(tempArray.size) // 用于记录X坐标
        var tempYArray = IntArray(tempArray.size) // 用于记录Y坐标


        // 获取圆形区域内的Y16数组
        var index = 0
        val radiusSquared = radius * radius
        for (y in centerY - radius..centerY + radius) {
            for (x in centerX - radius..centerX + radius) {
                val dx = x - centerX
                val dy = y - centerY
                val disSquared = dx * dx + dy * dy
                if (disSquared <= radiusSquared) {
                    // 确保 y 和 x 在 mY16Frame 的有效范围内
                    if (y in 0 until y16H && x in 0 until y16W) {
                        val pos = y * y16W + x
                        tempY16Array[index] = mY16Frame?.get(pos)!!
                        tempXArray[index] = x
                        tempYArray[index] = y
                        index++
                    }
                }
            }
        }

        // 调整 tempY16Array 的大小以匹配实际提取的元素数量
        tempY16Array = tempY16Array.copyOf(index)
        tempXArray = tempXArray.copyOf(index)
        tempYArray = tempYArray.copyOf(index)

        // 获取 maxY16 和 maxIndex
        val maxY16 = getMaxY16(tempY16Array)
        maxTempStr = guideInterface?.measureTemByY16(maxY16)!!
        maxX = tempXArray[maxIndex]
        maxY = tempYArray[maxIndex]
    }


    /**
     * 获取某个矩形区域内的温度矩阵
     */
    protected fun getOneRectTemp() {
        System.arraycopy(mY16Frame, 0, mSyncY16Frame, 0, mY16Frame?.size!!)
        if (guideInterface != null) {
            // 获取圆的外接正方形
            var index = 0
            val i1 = centerX - radius // 目标左上角坐标X
            val i2 = centerY - radius // 目标左上角坐标Y
            val w = 2 * radius // 目标宽
            val h = 2 * radius // 目标高
            val tempArray = FloatArray(w * h)
            val tempY16Array = ShortArray(w * h)
            val tempXArray = IntArray(tempArray.size) // 用于记录X坐标
            val tempYArray = IntArray(tempArray.size) // 用于记录Y坐标

            val distance = guideInterface?.distance.takeIf { it != -1f } ?: 1.5f

            // 获取某个区域的温度矩阵
            val ret = guideInterface?.getTempMatrix(
                mY16Frame,
                y16W,
                y16H,
                distance,
                i1,
                i2,
                w,
                h,
                tempArray
            )

            // 获取某个区域的Y16矩阵数组
            if (ret!!) {
                for (y in i2 until i2 + h) {
                    for (x in i1 until i1 + w) {
                        // 确保 y 和 x 在 mY16Frame 的有效范围内
                        if (y in 0 until y16H && x in 0 until y16W) {
                            val pos = y * y16W + x
                            tempY16Array[index] = mY16Frame!![pos]
                            tempXArray[index] = x
                            tempYArray[index] = y
                            index++
                        }
                    }
                }

                // 调整 tempY16Array 的大小以匹配实际提取的元素数量
                tempY16Array.copyInto(tempY16Array, 0, 0, index)
                tempXArray.copyInto(tempXArray, 0, 0, index)
                tempYArray.copyInto(tempYArray, 0, 0, index)

                // 获取 maxY16 和 maxIndex
                val maxY16 = getMaxY16(tempY16Array)
                maxTempStr = guideInterface?.measureTemByY16(maxY16)!!
                maxX = tempXArray[maxIndex]
                maxY = tempYArray[maxIndex]

                // 获取数据
                maxTempArray = tempArray.take(index).sortedDescending().take(10).map { it.toDouble() }.toList()
                vivoMaxTemp = guideInterface?.getHumanTemp(
                    maxTempStr.toFloatOrDefault(0f),
                    GuideInterface.DEFAULT_AMBIENT_TEMP
                )?.toDoubleOrNull()
            }



            // 获取某个矩形区域的温度数据
//        for (i in 0 until tempArray.lastIndex) {
//            val temp = BaseDataTypeConvertUtils.Companion.float2StrWithOneDecimal(tempArray[i])
//            result.append(temp).append("\t")
//        }
//        val tempLast = BaseDataTypeConvertUtils.Companion.float2StrWithOneDecimal(tempArray.last())
//        result.append(tempLast)
        }
        // 返回矩形框内的矩阵数据
//    return result.toString()
    }


}